<template>
  <div class="page search-page">
    <search-bar v-model="keyword" @change="onSearch" @onClear="clear" />
    <div class="auto-completion-wrap" v-show="completion.length >= 1">
      <ul>
        <li
          v-for="(item, index) in completion"
          :key="index"
          @click.stop="onSearch(item.suggestedKeyword, $event)"
        >{{item.suggestedKeyword}}</li>
      </ul>
    </div>
    <div class="content">
      <div class="search-default" v-if="!$route.query.keyword">
        <section-card title="热门搜索">
          <label-list :list="hotSearch" @onSelect="onSearch" />
        </section-card>
        <section-card title="历史搜索">
          <template v-slot:right>
            <a href="javascript:;" class="clear" @click="clearHistory">
              <icon name="sousuo" :size="30" />
              <span>清除历史记录</span>
            </a>
          </template>
          <label-list :list="historySearch" @onSelect="onSearch" />
        </section-card>
      </div>
      <div class="search-product" v-else>
        <p class="desc fl" v-if="products.length <= 0">很抱歉，没有找到<b>“{{$route.query.keyword}}”</b>商品，为您推荐今日热卖商品</p>
        <product-list
          v-else
          :list="products"
        />
      </div>
    </div>
  </div>
</template>

<script>
import SearchBar from './component/SearchBar'
import LabelList from './component/LabelList'
import scroll from '@/mixins/scroll'

export default {
  name: 'Search',
  mixins: [scroll],
  data () {
    return {
      keyword: this.$route.query.keyword || '',
      hotSearch: ['苹果', '白菜', '牛奶', '肉'],
      historySearch: JSON.parse(localStorage.getItem('historySearch')) || [],
      completion: [],
      loadFlg: false,
      products: [],
      fetchParams: {
        page: 0,
        pageSize: 10
      }
    }
  },
  components: {
    SearchBar,
    LabelList
  },
  watch: {
    keyword (newValue) {
      if (newValue && newValue !== this.$route.query.keyword) {
        this.serarchKey()
      } else {
        this.completion = []
      }
    },
    '$route' () {
      if (this.$route.query.keyword) {
        this.keyword = this.$route.query.keyword
        this.setHistory(this.keyword)
        this.getProductList()
      }
    }
  },
  created () {
    if (this.keyword) {
      this.getProductList()
      this.setHistory(this.keyword)
    }
  },
  methods: {
    serarchKey () {
      this.$api.product.serarchKey({
        keyword: this.keyword
      }).then((res) => {
        this.completion = res.data && res.data.suggestions
      })
    },

    async getProductList () {
      const list = await this.$api.product.list({
        ...this.fetchParams,
        keyword: this.keyword
      })
      if (this.fetchParams.page === 0) {
        this.products = list.data
      } else {
        this.products = this.products.concat(list.data)
      }
      this.loadFlg = false
    },

    onSearch (keyword = '', e) {
      this.completion = []
      this.$router.push({
        path: '/search',
        query: {
          keyword: typeof keyword === 'string' ? keyword : this.keyword
        }
      })
    },

    clear () {
      this.keyword = ''
      this.products = []
      if (this.$route.query.keyword) {
        this.$router.replace({
          path: '/search',
          query: {}
        })
      }
    },

    setHistory (val) {
      let historySearch = JSON.parse(localStorage.getItem('historySearch')) || []
      historySearch.push(val)
      historySearch = [...new Set(historySearch)]
      this.historySearch = historySearch
      localStorage.setItem('historySearch', JSON.stringify(historySearch))
    },

    clearHistory () {
      localStorage.removeItem('historySearch')
      this.historySearch = []
    },

    onScrollBottom () {
      if (this.loadFlg) return
      this.loadFlg = true
      this.fetchParams.page += 1
    }
  }
}
</script>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background: #fff;
  .auto-completion-wrap {
    position: fixed;
    top: 98px;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    overflow: auto;
    z-index: 100000;
  }
  .search-default {
    margin-top: 20px;
    .clear {
      @include flex(row, center, center);
      span {
        color: #999999;
        margin-right: 5px;
        font-size: 24px;
      }
    }
  }
}
</style>
